package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	. "golang-step/day28/model"
)

func main() {
	const DB_TYPE = "mysql"
	const DB_URL = "root:root@/go?charset=utf8&parseTime=True&loc=Local"
	//db,err := gorm.Open("mysql","root:root@/go?charset=utf8&parseTime=True&loc=Local")

	//自定义表前缀
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return "" + defaultTableName
	}

	//获取数据库连接
	db, err := gorm.Open(DB_TYPE, DB_URL)
	if err != nil {
		fmt.Println("database connect failed！")
		return
	}
	//关闭数据库
	defer db.Close()

	// Disable table name's pluralization, if set to true, `User`'s table name will be `user`
	db.SingularTable(true)

	// Migrate the schema
	//给表添加后缀
	db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").AutoMigrate(&Animal{})

	if !db.HasTable(&Animal{}) {

		if err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&Animal{}).Error; err != nil {
			panic(err)
		}
	}
	var animal = Animal{Age: 29, Name: "mark"}
	db.Create(&animal)

	//查询对象
	var animals = []Animal{}
	var animalVo Animal
	db.First(&animalVo, "age=?", 29)
	fmt.Println(animalVo)

	db.Find(&animals)
	fmt.Println("所有记录为：", animals)
	//更新记录
	db.Model(&animalVo).Update("age", 30).Where("name", "mark")
	db.First(&animalVo, "name=?", "mark")
	fmt.Println(animalVo)

}
